/* eslint-disable react/sort-comp */
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Card, Row, Col, Form, Button, Spin, Modal, Steps, message, Tabs, Table} from 'antd';
import {FORM_OPTIONS, PAGE, TABLE, FORM_ROW_OPTIONS} from '../constants';
import {formatMessage, injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import {getSourceOrders} from './api';
import Return from '../common/Return';
import styles from './style.css';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import DateRangePicker from 'Shared/components/DateRangePicker';
import {conventEnumValueToString, formatAmount, uuid} from '../utils';
import {currency} from '../Enum';
import {PERMISSION, dealerConditions} from './constants';
import TextArea from 'Shared/components/TextArea';
import routes from './routes';
import CommonDetailForAdd from './CommonDetailForAdd';
import TextInput from 'Shared/components/TextInput';
import moment from 'moment';
import {computeSelectedRows} from './utils';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const FormItem = Form.Item;
const Step = Steps.Step;
const TabPanel = Tabs.TabPane;
const EMPTY_ARRAY = [];
const autosize = {min: 1};

class AdjustPanel extends Component {
    state = {
        queryCondition: {
            financeApproveTime: [],
            submitTime: [],
            productCategoryCodes: [],
            manucturerId: undefined
        },
        data: {},
        isSubmitting: false,
        isFetching: false,
        hasOperat: false,
        currentStep: 0,
        activeKey: 'claims',
        showPanel: false,
        currentId: '',
        selectedRowKeys: [],
        selectedRows: [],
    };
    componentDidMount() {
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }
    onClickReturnBtn = () => {
        this.props.history.push(routes.query.url());
    };
    
    onChange = (value, name) => {
        this.setState({
            queryCondition: {
                ...this.state.queryCondition,
                [name]: value,
            },
            hasOperat: true
        });
    };

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }

    onSelectDealer = (data = {}) => {
        this.setState({
            queryCondition: {
                ...this.state.queryCondition,
                dealerId: data.id,
                dealerCode: data.code,
                dealerName: data.name,
            },
            hasOperat: true
        });
    }
    getSettlementSourceOrders = condition => {
        this.setState({
            isFetching: true
        });
        const {dealerCode, dealerName, ...props} = condition;
        getSourceOrders(props).then(res => {
            if(res.ok) {
                const {claims = []} = res.data || {};
                this.setState({
                    data: {
                        claims: claims.map(item => ({
                            id: uuid(),
                            ...item,
                            department: '服务支援部'
                        })),
                    }
                });
            }
            this.setState({
                isFetching: false
            });
        });
    };

    expenseRowKey = record => `${record.dealerCode}${record.currency}`
    claimRowKey = record => `${record.dealerCode}${record.currency}${record.manufacturerName}`
    onClickNextStep = () => {
        this.setState({
            currentStep: this.state.currentStep + 1
        });
        const queryCondition = this.state.queryCondition;
        const condition = {
            brandId: queryCondition.brandId,
            dealerId: queryCondition.dealerId,
            productCategoryCodes: queryCondition.productCategoryCodes,
            manucturerId: queryCondition.manucturerId
        };
        if(queryCondition.financeApproveTime && queryCondition.financeApproveTime.length > 0) {
            condition.beginFinanceApproveTime = moment(queryCondition.financeApproveTime[0]).toISOString();
            condition.endFinanceApproveTime = moment(queryCondition.financeApproveTime[1]).toISOString();
        }
        if(queryCondition.submitTime && queryCondition.submitTime.length > 0) {
            condition.beginSubmitTime = moment(queryCondition.submitTime[0]).toISOString();
            condition.endSubmitTime = moment(queryCondition.submitTime[1]).toISOString();
        }
        this.getSettlementSourceOrders(condition);
    };
    onClickPrevStep = () => {
        Modal.confirm({
            title: formatMessage({
                id: 'adjustPanel.prevStep.confim.title',
                defaultMessage: '切换到上一步'
            }),
            content: formatMessage({
                id: 'adjustPanel.prevStep.confim.content',
                defaultMessage: '切换到上一步，将会清空当前清单数据，是否继续？'
            }),
            onOk: () => {
                this.setState({
                    currentStep: this.state.currentStep - 1,
                    data: {}
                });
            }
        });
    };
    onSubmit = () => {
        const {claims = []} = this.state.data;
        if(!claims.length)
            return message.warn(formatMessage({
                id: 'adjustPanel.onSubmit.content',
                defaultMessage: '当前没有可预结算的单据，请返回上一步重新查询'
            }));
        if(!this.state.selectedRows.length)
            return message.warn(formatMessage({
                id: 'adjustPanel.onSubmit.details',
                defaultMessage: '请选择要结算的总代'
            }));
        this.setState({
            isSubmitting: true
        });
        return this.props.onSubmit(this.state.selectedRows).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    isSubmitting: false
                });
        });
    };

    onChangeTabs = activeKey => {
        this.setState({activeKey});
    }

    onChangeRemark = (value, id) => {
        const details = this.state.data[this.state.activeKey] || EMPTY_ARRAY;
        const tmp = details.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    remark: value
                };
            return order;
        });
        this.setState({
            data: {
                ...this.state.data,
                [this.state.activeKey]: tmp
            },
            hasOperat: true
        });
    };

    onChangeDepartment = (value, id) => {
        const details = this.state.data[this.state.activeKey];
        const tmp = details.map(order => {
            if(order.id === id)
                return {
                    ...order,
                    department: value
                };
            return order;
        });
        this.setState({
            data: {
                ...this.state.data,
                [this.state.activeKey]: tmp
            },
            hasOperat: true
        });
    };

    onClickDetail = e => {
        const {id} = e.target.dataset;
        this.setState({
            showPanel: true,
            currentId: id
        });
    }

    onCloaseModal = () => {
        this.setState({
            showPanel: false,
            currentId: ''
        });
    }
    render() {
        const languageIntl = language;
        const {queryCondition, isFetching, isSubmitting, activeKey} = this.state;
        const {claims = []} = this.state.data;
        const dealerInfo = queryCondition.dealerId ? {
            id: queryCondition.dealerId,
            code: queryCondition.dealerCode,
            name: queryCondition.dealerName,
        } : null;

        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'adjustPanel.column.dealerCode',
                    defaultMessage: '总代ERP号'
                }),
                dataIndex: 'dealerCode',
                width: languageIntl === 'pt-PT' ? 230 : 150,
                render: (text, record) => <a onClick={this.onClickDetail} data-id={record.id}>{text}</a>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brand',
                    defaultMessage: '品牌'
                }),
                sorter: true,
                dataIndex: 'brand',
                width: 120,
                render: (text, record) => `(${record.brandCode})${record.brandName}`
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'adjustPanel.column.department',
                    defaultMessage: '报销部门'
                }),
                dataIndex: 'department',
                className: styles.formEdit,
                width: 230,
                render: (text, record) => (
                    <FormItem>
                        <TextInput
                            type="textarea"
                            autosize={autosize}
                            id={record.id} value={record.department} onBlur={this.onChangeDepartment} />
                    </FormItem>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'adjustPanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
                className: styles.formEdit,
                width: 230,
                render: (text, record) => (
                    <FormItem>
                        <TextInput
                            type="textarea"
                            autosize={autosize}
                            id={record.id} value={record.remark} onBlur={this.onChangeRemark} />
                    </FormItem>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'adjustPanel.column.currency',
                    defaultMessage: ' 币种'
                }),
                dataIndex: 'currency',
                width: 120,
                render: text => conventEnumValueToString(currency, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'adjustPanel.column.tradeMethodName',
                    defaultMessage: '贸易方式'
                }),
                dataIndex: 'tradeMethodName',
                width: 180,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'adjustPanel.column.manufacturerName',
                    defaultMessage: '生产工厂'
                }),
                dataIndex: 'manufacturerName',
                width: 130,
            },
        ];
        if(!this.props.isMoneyVisible)
            columns.splice(7, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'adjustPanel.column.materialFee',
                        defaultMessage: '材料费'
                    }),
                    dataIndex: 'materialFee',
                    width: 150,
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'adjustPanel.column.mgmtFee',
                        defaultMessage: '管理费'
                    }),
                    dataIndex: 'mgmtFee',
                    width: 150,
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'adjustPanel.column.laborFee',
                        defaultMessage: '工时费'
                    }),
                    dataIndex: 'laborFee',
                    width: languageIntl === 'pt-PT' ? 190 : 120,
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'adjustPanel.column.assistantFee',
                        defaultMessage: '辅料费'
                    }),
                    dataIndex: 'assistantFee',
                    className: styles.textAlign,
                    width: languageIntl === 'pt-PT' ? 180 : 120,
                    render: text => formatAmount(text)
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'adjustPanel.column.totalFee',
                        defaultMessage: '费用合计'
                    }),
                    dataIndex: 'totalFee',
                    sorter: true,
                    width: 130,
                    className: styles.textAlign,
                    render: text => formatAmount(text)
                });
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            }
        };
        const data = this.state.data[activeKey] || EMPTY_ARRAY;
        const detailData = data.find(item => item.id === this.state.currentId) || {};
        const steps = [
            {
                title: formatMessage({
                    id: 'adjustPanel.steps.1.title',
                    defaultMessage: '输入查询条件'
                }),
                content: (
                    <div>
                        <Card className="form-standard">
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'queryPanel.dealer',
                                            defaultMessage: '总代ERP号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <DealerSelectPanel
                                            conditions={dealerConditions}
                                            value={dealerInfo}
                                            onSelect={this.onSelectDealer} />
                                    </FormItem>
                                </Col>
                                {this.props.brands.length > 1 && (
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'queryPanel.brand',
                                                defaultMessage: '品牌'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                name="brandId"
                                                value={queryCondition.brandId}
                                                options={this.props.brands}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                )}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'queryPanel.manucturerId',
                                            defaultMessage: '生产工厂	'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="manucturerId"
                                            value={queryCondition.manucturerId}
                                            options={this.props.manucturers}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'queryPanel.submitTime',
                                            defaultMessage: '提交时间'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <DateRangePicker name="submitTime" value={queryCondition.submitTime}
                                            onChange={this.onChange} disabled={queryCondition.financeApproveTime.length > 0}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'queryPanel.approveTime',
                                            defaultMessage: '审核时间'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <DateRangePicker name="financeApproveTime" value={queryCondition.financeApproveTime}
                                            onChange={this.onChange} disabled={queryCondition.submitTime.length > 0}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'queryPanel.productCategoryCode',
                                            defaultMessage: '车型编号'
                                        })}
                                        {...FORM_ROW_OPTIONS.item}>
                                        <TextArea
                                            name="productCategoryCodes"
                                            placeholder={formatMessage({
                                                id: 'queryPanel.form.productCategoryCode.placeholder',
                                                defaultMessage: '最多输入1000个车型编号，以回车隔开'
                                            })}
                                            value={queryCondition.productCategoryType}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card className={styles.optionBtn}>
                            <Button
                                type="primary"
                                onClick={this.onClickNextStep}>
                                {formatMessage({
                                    id: 'btn.nextStep',
                                    defaultMessage: '下一步'
                                })}
                            </Button>
                        </Card>
                    </div>
                )
            },
            {
                title: formatMessage({
                    id: 'adjustPanel.steps.2.title',
                    defaultMessage: '预结算单据'
                }),
                content: (
                    <React.Fragment>

                        <Modal
                            title={this.props.intl.formatMessage({
                                id: 'add.detail.modal.title',
                                defaultMessage: '索赔预结算详情'
                            })}
                            width="80%"
                            maskClosable={false}
                            footer={null}
                            wrapClassName={styles.dataSelectModal}
                            destroyOnClose={true}
                            visible={this.state.showPanel}
                            onCancel={this.onCloaseModal}>
                            <CommonDetailForAdd
                                detail={detailData}
                                tabName={activeKey}
                                showBrand={this.props.showBrand}
                                isMoneyVisible={this.props.isMoneyVisible}
                                isDealerUser={this.props.isDealerUser} />
                        </Modal>
                        <Spin spinning={isFetching || isSubmitting}>
                            <Card title={this.props.intl.formatMessage({
                                id: 'detail.detail.title',
                                defaultMessage: '预结算单据'
                            })}>
                                <Tabs onChange={this.onChangeTabs}>
                                    <TabPanel
                                        tab={`${this.props.intl.formatMessage({
                                            id: 'detail.claims.title',
                                            defaultMessage: '索赔单'
                                        })}(${claims.length})`}
                                        key="claims">
                                        <Table
                                            className="white-space-nowrap"
                                            rowKey="id"
                                            columns={columns}
                                            pagination={false}
                                            dataSource={claims}
                                            rowSelection={rowSelection}
                                            scroll={{
                                                x: 'max-content',
                                                y: 430}}
                                            size="small"
                                            bordered={true}/>
                                    </TabPanel>
                                </Tabs>
                            </Card>
                            <Card className={styles.optionBtn}>
                                <Button
                                    type="primary"
                                    onClick={this.onClickPrevStep}>
                                    {formatMessage({
                                        id: 'btn.prevStep',
                                        defaultMessage: '上一步'
                                    })}
                                </Button>
                                <Button
                                    type="primary"
                                    onClick={this.onSubmit}
                                    disabled={!this.props.submitable}
                                    loading={isSubmitting}>
                                    {formatMessage({
                                        id: 'btn.submit',
                                        defaultMessage: '提交'
                                    })}
                                </Button>
                            </Card>
                        </Spin>
                    </React.Fragment>
                )
            }
        ];
        return (
            <div>
                <Card className="card-full-width">
                    <Steps current={this.state.currentStep}>
                        {steps.map(item => (
                            <Step key={item.title} title={item.title} />
                        ))}
                    </Steps>
                </Card>
                {steps[this.state.currentStep].content}
                <div className="page-toolbar">
                    <Return
                        disabled={isSubmitting}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel}/>
                </div>
            </div>
        );
    }
}

AdjustPanel.propTypes = {
    brands: PropTypes.array,
    history: PropTypes.object,
    isMoneyVisible: PropTypes.bool,
    manucturers: PropTypes.array,
    pagePermission: PropTypes.array,
    refreshListData: PropTypes.func,
};

import {
    clearData,
    tableSearch,
    onClickNew,
} from './actions';
import {createSelector} from 'reselect';
import {connect} from 'react-redux';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    permissions => {
        const data = permissions.toJS();
        return data.includes(PERMISSION.add);
    }
);
const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        }));
    }
);

const getManucturersData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'manucturers']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        }));
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    brands: getBrandsData(state),
    submitable: getPermissions(state, ownProps),
    manucturers: getManucturersData(state),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    conditions: getSubmitData(state),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    showBrand: state.getIn(['page', 'domainData', 'brands', 'data']).size > 1,
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onSubmit: data =>
        dispatch(onClickNew(data)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(AdjustPanel));
